package com.example.bank.service.client;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.example.bank.dao.ClientDao;
import com.example.bank.dao.ImageDao;
import com.example.bank.dao.UnionDao;
import com.example.bank.dao.UserDao;
import com.example.bank.pojo.Client;
import com.example.bank.exception.SystemException;
import com.example.bank.pojo.ClientQuery;
import com.example.bank.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * @author ：Leeziqiang
 * @description：ClientServiceImpl实现类
 * @date ：2021/12/4 9:19
 */
@Service
@Transactional
public class ClientServiceImpl implements ClientService{

    private static final Logger logger = LoggerFactory.getLogger(ClientServiceImpl.class);

    @Autowired
    private ClientDao clientDao;
    @Autowired
    private UnionDao unionDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ImageDao imageDao;

    @Override
    public Client findById(String id) {
        if (StrUtil.isEmpty(id)) {
            throw new SystemException("客户id为空");
        }
        Client client = clientDao.findById(id);
        if (ObjectUtil.isNull(client)) {
            return null;
        }
        // 根据客户名字查询业务员
        String userId = unionDao.findUserByClient(id);
        String user = userDao.findNameById(userId);
        client.setSalesman(user);
        return client;
    }

    @Override
    public String findSalesman(String id) {
        // 根据客户名字查询业务员
        String userId = unionDao.findUserByClient(id);
        String user = userDao.findNameById(userId);
        return user;
    }

    @Override
    public String findByNumber(String clientIdNumber) {
        if (StrUtil.isEmpty(clientIdNumber)) {
            throw new SystemException("param error");
        }
        return clientDao.findByNumber(clientIdNumber);
    }

    @Override
    public String findNumberById(String clientId) {
        if (StrUtil.isEmpty(clientId)) {
            throw new SystemException("param error");
        }
        return clientDao.findNumberById(clientId);
    }

    @Override
    public Client addClient(Client client) {
        logger.info("----------addClient执行，添加一个客户----------");
//        String id = UUID.randomUUID().toString();
//        client.setClientId(id);
        int n = clientDao.saveClient(client);
        if (n > 0) {
            return client;
        }
        return null;
    }

    @Override
    public List<Client> listClients(List<String> ids) {
        if (ObjectUtil.isEmpty(ids)) {
            throw new SystemException("param error");
        }
        List<Client> clients = clientDao.findByIds(ids);
        return clients;
    }

    @Override
    public List<Client> listClients(List<String> ids, Integer approvalState) {
        if (ObjectUtil.isEmpty(ids) || ObjectUtil.isNull(approvalState)) {
            throw new SystemException("param error");
        }
        List<Client> clients = clientDao.findByState(ids, approvalState);
        return clients;
    }

    @Override
    public boolean updateClientState(String clientId, Integer state) {
        if (StrUtil.isEmpty(clientId) || ObjectUtil.isNull(state)) {
            throw new SystemException("param error");
        }
        int n = clientDao.updateApprovalState(clientId, state);
        if (n > 0) {
            return true;
        }
        return false;
    }


    @Override
    public List<Client> listAll() {
        List<Client> clients = clientDao.list();
        for (Client client : clients) {
            if (ObjectUtil.isNotNull(client)) {
                // 根据客户名字查询业务员
                String userId = unionDao.findUserByClient(client.getClientId());
                String user = userDao.findNameById(userId);
                client.setSalesman(user);
            }
        }
        return clients;
    }

    @Override
    public boolean updateDeadline(String clientId, String deadline, Integer state) {
        if (StrUtil.isEmpty(clientId) || ObjectUtil.isNull(state)) {
            throw new SystemException("param error");
        }
        int n = clientDao.updateDeadline(clientId, deadline, state);
        if (n > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<Client> query(String salesman, String bankArea, Integer approvalState) {
        List<User> users = userDao.findByName(salesman);
        logger.info("users:"+users.toString());
        List<Client> clients = new ArrayList<>();
        for (User user : users) {
            if (user == null) {
                return new ArrayList<Client>();
            }
            List<String> clientIds = unionDao.findClientByUserId(user.getUserId());
            for (String clientId : clientIds) {
                logger.info(clientDao.findByQuery(clientId, bankArea, approvalState).toString());
                clients.addAll(clientDao.findByQuery(clientId, bankArea, approvalState));
            }
        }
        return clients;
    }

    @Override
    public List<Client> listByClientQuery(ClientQuery clientQuery, List<String> ids) {
        if (clientQuery == null) {
            clientQuery = new ClientQuery();
        }
        List<Client> clients = clientDao.findByClientQuery(clientQuery.getBankArea(), clientQuery.getApprovalState(), clientQuery.getOrderTime1(), clientQuery.getOrderTime2(), ids);
        if (ObjectUtil.isNotNull(clients)) {
            for (Client client : clients) {
                String userId = unionDao.findUserByClient(client.getClientId());
                String user = userDao.findNameById(userId);
                client.setSalesman(user);
            }
        }
        if (clientQuery.getUsername() == null || "".equals(clientQuery.getUsername())) {
            // 不做处理
        } else {
            Iterator<Client> iterator = clients.iterator();
            while (iterator.hasNext()) {
                Client client = iterator.next();
                if (!client.getSalesman().equals(clientQuery.getUsername())) {
                    iterator.remove();
                }
            }
        }
        return clients;
    }

    // 更改客户信息，当订单被经理拒绝后
    @Override
    public boolean updateClient(Client client) {
        // 更改tbl_client中的客户信息
        int n = clientDao.updateClient(client);
        if (n > 0) {
            return true;
        }
        return false;
    }

    // 删除客户信息
    @Override
    public boolean deleteClient(String id) {
        if (StrUtil.isEmpty(id)) {
            throw new SystemException("客户id为空");
        }
        // 删除tbl_image中的客户照片
        // 根据客户id查询身份证号码
        String clientIdNumber = clientDao.findNumberById(id);
        // 查询图片的名字
        List<String> imageNames = imageDao.findNameByIdNumber(clientIdNumber);
        // 删除文件夹中的图片
        for (String imageName : imageNames) {
            File file = new File(imageName);
            file.delete();
        }
        // 删除数据库表中的图片记录
        int l = imageDao.remove(clientIdNumber);
        // 删除tbl_client中的客户信息
        int m = clientDao.removeClient(id);
        // 删除tbl_user_client中的关联关系
        int n = unionDao.remove(id);
//        if (l > 0 && m > 0 && n > 0) {
//            return true;
//        }
//        return false;
        return true;
    }

    @Override
    public boolean updateQueryState(String id) {
        int n = clientDao.updateQueryState(id);
        if (n > 0) {
            return true;
        }
        return false;
    }


}
